<template>
  <div class="material-purchase-manage">
    <!-- 查询区域 -->
    <el-form :inline="true" :model="searchForm" class="search-form" @submit.prevent>
      <el-form-item label="采购ID">
        <el-input v-model="searchForm.purchaseId" placeholder="请输入采购ID" clearable />
      </el-form-item>
      <el-form-item label="物料名称">
        <el-input v-model="searchForm.materialName" placeholder="请输入物料名称" clearable />
      </el-form-item>
      <el-form-item label="供应商ID">
        <el-input v-model="searchForm.providerId" placeholder="请输入供应商ID" clearable />
      </el-form-item>
      <el-form-item label="采购日期">
        <el-date-picker
          v-model="searchForm.purchaseDate"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item label="审核状态">
        <el-select v-model="searchForm.auditStatus" placeholder="请选择审核状态" clearable style="width: 100px;">
          <el-option label="未审核" :value="0" />
          <el-option label="已通过" :value="1" />
          <el-option label="已拒绝" :value="2" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="部门">
        <el-select v-model="searchForm.deptId" placeholder="请选择部门" clearable filterable style="width: 200px;" @change="handleDeptChange">
          <el-option v-for="dept in deptList" :key="dept.deptId" :label="dept.deptName" :value="dept.deptId" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="人员">
        <el-select v-model="searchForm.personId" placeholder="请选择人员" clearable filterable :loading="loading">
          <el-option v-for="person in deptPersons" :key="person.personId" :label="person.personName + '（' + person.personId + '）'" :value="person.personId" />
            <!-- <el-empty v-if="!loading && deptPersons.length === 0" description="暂无人员"/> -->
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
      <!-- 根据用户角色显示不同的操作按钮 -->
      <el-form-item v-if="userRole === '普通操作人员'">
        <el-button type="success" @click="showAddDialog = true">新增采购申请</el-button>
      </el-form-item>
    </el-form>

    <!-- 物料采购列表 -->
    <el-table :data="purchaseList" border>
      <el-table-column prop="purchaseId" label="采购ID" min-width="80" />
      <el-table-column prop="materialName" label="物料名称" min-width="120" />
      <el-table-column prop="deptName" label="部门" min-width="80" />
      <el-table-column prop="personName" label="人员" min-width="80" />
      <el-table-column prop="purchaseQuantity" label="采购数量" min-width="100" />
      <el-table-column prop="actualQuantity" label="实际数量" min-width="100" />
      <!-- 隐藏采购原因、审核意见和附加信息列 -->
      <!-- <el-table-column prop="purchaseReason" label="采购原因" min-width="150" /> -->
      <el-table-column prop="auditStatus" label="审核状态" min-width="100">
        <template #default="{ row }">
          <el-tag :type="getAuditStatusType(row.auditStatus)">
            {{ getAuditStatusText(row.auditStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <!-- <el-table-column prop="auditComment" label="审核意见" min-width="150" /> -->
      <!-- <el-table-column prop="additionalInfo" label="附加信息" min-width="150" /> -->
      <el-table-column prop="createTime" label="创建时间" min-width="140" :formatter="formatDateTime" />
      <el-table-column prop="updateTime" label="更新时间" min-width="140" :formatter="formatDateTime" />
      <el-table-column prop="providerName" label="供应商名称" min-width="120" />
      <el-table-column prop="purchaserName" label="采购人" min-width="100" />
      <el-table-column label="操作" min-width="220">
        <template #default="{ row }">
          <!-- 添加详情按钮 -->
          <el-button size="small" @click="showDetail(row)">详情</el-button>
          <!-- 普通操作人员可以修改未审核或被拒绝的采购申请 -->
          <el-button 
            v-if="userRole === '普通操作人员' && row.auditStatus === 0 || row.auditStatus === 2" 
            size="small" 
            type="primary" 
            @click="handleEditPurchase(row)"
          >
            修改
          </el-button>
          <!-- 部门经理可以审批采购申请 -->
          <el-button 
            v-if="userRole === '部门经理' && row.auditStatus === 0" 
            size="small" 
            type="success" 
            @click="handleAudit(row, 1)"
          >
            通过
          </el-button>
          <el-button 
            v-if="userRole === '部门经理' && row.auditStatus === 0" 
            size="small" 
            type="danger" 
            @click="handleAudit(row, 2)"
          >
            拒绝
          </el-button>
          <!-- 系统管理员和普通操作人员可以录入实际生产数量 -->
          <el-button 
            v-if="userRole === '系统管理员' || userRole === '普通操作人员' && row.auditStatus === 1" 
            size="small" 
            type="warning" 
            @click="handleUpdateActualQuantity(row)"
          >
            录入实际数量
          </el-button>
          <!-- 所有角色都可以删除 -->
          <el-button 
            size="small" 
            type="danger" 
            @click="handleDeletePurchase(row.purchaseId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
      background
      layout="prev, pager, next, jumper, ->, total"
      :total="pagination.total"
      :page-size="pagination.size"
      :current-page="pagination.current"
      @current-change="handlePageChange"
    />

    <!-- 添加/修改物料采购对话框 -->
    <el-dialog :title="editPurchaseId ? '修改采购申请' : '新增采购申请'" v-model="showAddDialog">
      <el-form :model="addForm" :rules="rules" ref="addFormRef" label-width="120px">
        <el-form-item label="物料名称" prop="materialName">
          <el-input v-model="addForm.materialName" />
        </el-form-item>
        <!-- <el-form-item label="部门" prop="deptId">
          <el-select v-model="addForm.deptId" placeholder="请选择部门" @change="handleDeptChange">
            <el-option v-for="dept in deptList" :key="dept.deptId" :label="dept.deptName" :value="dept.deptId" />
          </el-select>
        </el-form-item>
        <el-form-item label="人员" prop="personId">
          <el-select v-model="addForm.personId" placeholder="请选择人员">
            <el-option v-for="person in deptPersons" :key="person.personId" :label="person.personName + '（' + person.personId + '）'" :value="person.personId" />
            <el-empty v-if="!loading && deptPersons.length === 0" description="暂无人员"/>
          </el-select>
        </el-form-item> -->
        <el-form-item label="采购数量" prop="purchaseQuantity">
          <el-input-number v-model="addForm.purchaseQuantity" :min="0" />
        </el-form-item>
        <el-form-item label="采购原因" prop="purchaseReason">
          <el-input v-model="addForm.purchaseReason" type="textarea" />
        </el-form-item>
        <el-form-item label="附加信息" prop="additionalInfo">
          <el-input v-model="addForm.additionalInfo" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false; editPurchaseId = null">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 审核对话框 -->
    <el-dialog title="审核采购申请" v-model="showAuditDialog">
      <el-form :model="auditForm" ref="auditFormRef" label-width="120px">
        <el-form-item label="审核意见" prop="auditComment">
          <el-input v-model="auditForm.auditComment" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAuditDialog = false">取消</el-button>
        <el-button type="primary" @click="submitAudit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 录入实际数量对话框 -->
    <el-dialog title="录入实际生产数量" v-model="showActualQuantityDialog">
      <el-form :model="actualQuantityForm" ref="actualQuantityFormRef" label-width="120px">
        <el-form-item label="实际数量" prop="actualQuantity">
          <el-input-number v-model="actualQuantityForm.actualQuantity" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showActualQuantityDialog = false">取消</el-button>
        <el-button type="primary" @click="submitActualQuantity">确定</el-button>
      </template>
    </el-dialog>

    <!-- 增加生产计划对话框 -->
    <el-dialog title="增加生产计划" v-model="showAddPlanDialog">
      <el-form :model="addPlanForm" ref="addPlanFormRef" label-width="120px">
        <el-form-item label="计划名称" prop="planName">
          <el-input v-model="addPlanForm.planName" />
        </el-form-item>
        <el-form-item label="计划描述" prop="planDescription">
          <el-input v-model="addPlanForm.planDescription" type="textarea" />
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker v-model="addPlanForm.startDate" type="date" placeholder="选择日期" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker v-model="addPlanForm.endDate" type="date" placeholder="选择日期" style="width: 100%;" />
        </el-form-item>
        <el-form-item label="计划数量" prop="planQuantity">
          <el-input-number v-model="addPlanForm.planQuantity" :min="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddPlanDialog = false">取消</el-button>
        <el-button type="primary" @click="submitAddPlan">确定</el-button>
      </template>
    </el-dialog>

    <!-- 采购详情对话框 -->
    <el-dialog title="采购详情" v-model="showDetailDialog">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="采购ID">{{ selectedPurchase.purchaseId }}</el-descriptions-item>
        <el-descriptions-item label="物料名称">{{ selectedPurchase.materialName }}</el-descriptions-item>
        <el-descriptions-item label="部门ID">{{ selectedPurchase.deptId }}</el-descriptions-item>
        <el-descriptions-item label="人员ID">{{ selectedPurchase.personId }}</el-descriptions-item>
        <el-descriptions-item label="采购数量">{{ selectedPurchase.purchaseQuantity }}</el-descriptions-item>
        <el-descriptions-item label="实际数量">{{ selectedPurchase.actualQuantity }}</el-descriptions-item>
        <el-descriptions-item label="采购原因">{{ selectedPurchase.purchaseReason }}</el-descriptions-item>
        <el-descriptions-item label="审核状态">{{ getAuditStatusText(selectedPurchase.auditStatus) }}</el-descriptions-item>
        <el-descriptions-item label="审核意见">{{ selectedPurchase.auditComment }}</el-descriptions-item>
        <el-descriptions-item label="附加信息">{{ selectedPurchase.additionalInfo }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDateTime(null, null, selectedPurchase.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ formatDateTime(null, null, selectedPurchase.updateTime) }}</el-descriptions-item>
        <el-descriptions-item label="供应商名称">{{ selectedPurchase.providerName }}</el-descriptions-item>
        <el-descriptions-item label="采购人">{{ selectedPurchase.purchaserName }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useUserStore } from '@/stores/user'

// 从Pinia获取用户信息
const userStore = useUserStore()
const userRole = computed(() => userStore.userInfo?.title || '普通操作人员')
const userId = computed(() => userStore.userInfo?.id || 0)
const userDeptId = computed(() => userStore.userInfo?.deptId || 0)

// 搜索表单
const searchForm = reactive({
  purchaseId: '',
  materialName: '',
  providerId: '',
  purchaseDate: [],
  auditStatus: '',
  deptId: '',
  personId: ''
})

// 部门列表和部门人员列表
const deptList = ref([])
const deptPersons = ref([])
const loading = ref(false)

// 获取部门列表
const fetchDeptList = async () => {
  try {
    const res = await axios.get(import.meta.env.VITE_API_URL + 'dept/list')
    deptList.value = res.data.map(dept => ({
      deptId: dept.id,
      deptName: dept.deptName
    }))
    
  } catch (e) {
    ElMessage.error('获取部门列表失败')
  }
}

// 获取部门人员列表
const fetchDeptPersons = async (deptId: number) => {
  try {
    const res = await axios.get(import.meta.env.VITE_API_URL + 'person/getByDept', {
      params: { deptId: Number(deptId) }
    })
    console.log(1);
    
    console.log(res.data);
    
    deptPersons.value = res.data
  } catch (e) {
    ElMessage.error('获取部门人员列表失败')
  }
}

// 部门选择变化时获取该部门的人员列表
const handleDeptChange = (deptId: number) => {  
  if (deptId) {
    loading.value = true
    fetchDeptPersons(deptId).finally(() => loading.value = false)
  } else {
    deptPersons.value = []
  }
}

// 添加/修改表单
const addForm = reactive({
  materialName: '',
  deptId: userDeptId.value,
  personId: userId.value,
  // deptId: userDeptId.value,
  // personId: userId.value,
  purchaseQuantity: 0,
  actualQuantity: 0,
  purchaseReason: '',
  auditStatus: 0,
  auditComment: '',
  additionalInfo: ''
})

// 审核表单
const auditForm = reactive({
  purchaseId: null,
  auditStatus: 0,
  auditComment: ''
})

// 实际数量表单
const actualQuantityForm = reactive({
  purchaseId: null,
  actualQuantity: 0
})

// 生产计划表单
const addPlanForm = reactive({
  planName: '',
  planDescription: '',
  startDate: '',
  endDate: '',
  planQuantity: 0
})

// 表单验证规则
const rules = {
  materialName: [{ required: true, message: '请输入物料名称', trigger: 'blur' }],
  deptId: [{ required: true, message: '请输入部门ID', trigger: 'blur' }],
  personId: [{ required: true, message: '请输入人员ID', trigger: 'blur' }],
  purchaseQuantity: [{ required: true, message: '请输入采购数量', trigger: 'blur' }],
  purchaseReason: [{ required: true, message: '请输入采购原因', trigger: 'blur' }]
}

// 数据列表和分页
const purchaseList = ref([])
const pagination = reactive({
  total: 0,
  size: 10,
  current: 1
})

// 对话框控制
const showAddDialog = ref(false)
const showAuditDialog = ref(false)
const showActualQuantityDialog = ref(false)
const showAddPlanDialog = ref(false)
const showDetailDialog = ref(false) // 新增详情对话框控制
const editPurchaseId = ref(null)
const selectedPurchase = ref({}) // 新增用于存储选中采购详情的数据

// 表单引用
const addFormRef = ref(null)
const auditFormRef = ref(null)
const actualQuantityFormRef = ref(null)
const addPlanFormRef = ref(null)

// 获取审核状态文本
const getAuditStatusText = (status) => {
  switch (status) {
    case 0: return '未审核'
    case 1: return '已通过'
    case 2: return '已拒绝'
    default: return '未知状态'
  }
}

// 获取审核状态标签类型
const getAuditStatusType = (status) => {
  switch (status) {
    case 0: return 'info'
    case 1: return 'success'
    case 2: return 'danger'
    default: return 'info'
  }
}

// 格式化日期时间
const formatDateTime = (row, column, cellValue) => {
  if (!cellValue) return ''
  const date = new Date(cellValue)
  const year = date.getFullYear()
  const month = ('0' + (date.getMonth() + 1)).slice(-2)
  const day = ('0' + date.getDate()).slice(-2)
  const hours = ('0' + date.getHours()).slice(-2)
  const minutes = ('0' + date.getMinutes()).slice(-2)
  const seconds = ('0' + date.getSeconds()).slice(-2)
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 获取物料采购列表
const fetchPurchases = async (pageNum = 1) => {
  try {
    const params = {
      purchaseId: searchForm.purchaseId ? parseInt(searchForm.purchaseId) : null,
      materialName: searchForm.materialName || null,
      providerId: searchForm.providerId ? parseInt(searchForm.providerId) : null,
      purchaseDateStart: searchForm.purchaseDate?.[0] || null,
      purchaseDateEnd: searchForm.purchaseDate?.[1] || null,
      auditStatus: searchForm.auditStatus !== '' ? parseInt(searchForm.auditStatus) : null,
      // deptId: searchForm.deptId ? parseInt(searchForm.deptId) : null,
      deptId: userDeptId.value,
      personId: searchForm.personId ? parseInt(searchForm.personId) : null
    }
    const res = await axios.post(
      import.meta.env.VITE_API_URL + `materialPurchase/page?pageNum=${pageNum}&pageSize=${pagination.size}`,
      params
    )
    purchaseList.value = res.data.records
    pagination.total = res.data.total
    pagination.current = res.data.current
    pagination.size = res.data.size
  } catch (e) {
    console.error(e)
    ElMessage.error('获取物料采购数据失败')
  }
}

// 搜索处理
const handleSearch = () => {
  fetchPurchases(1)
}

// 重置搜索
const resetSearch = () => {
  searchForm.purchaseId = ''
  searchForm.materialName = ''
  searchForm.providerId = ''
  searchForm.purchaseDate = []
  searchForm.auditStatus = ''
  searchForm.deptId = ''
  searchForm.personId = ''
  fetchPurchases(1)
}

// 分页处理
const handlePageChange = (page) => {
  fetchPurchases(page)
}

// 编辑物料采购
const handleEditPurchase = (row) => {
  Object.assign(addForm, {
    materialName: row.materialName,
    deptId: row.deptId,
    personId: row.personId,
    purchaseQuantity: row.purchaseQuantity,
    purchaseReason: row.purchaseReason,
    additionalInfo: row.additionalInfo
  })
  editPurchaseId.value = row.purchaseId
  showAddDialog.value = true
}

// 删除物料采购
const handleDeletePurchase = async (purchaseId) => {
  try {
    await axios.delete(import.meta.env.VITE_API_URL + `materialPurchase/${purchaseId}`)
    ElMessage.success('删除成功')
    fetchPurchases(pagination.current)
  } catch (e) {
    console.error(e)
    ElMessage.error('删除失败')
  }
}

// 审核物料采购
const handleAudit = (row, status) => {
  auditForm.purchaseId = row.purchaseId
  auditForm.auditStatus = status
  auditForm.auditComment = ''
  showAuditDialog.value = true
}

// 提交审核
const submitAudit = async () => {
  try {
    await axios.post(
      import.meta.env.VITE_API_URL + `materialPurchase/audit/${auditForm.purchaseId}?auditStatus=${auditForm.auditStatus}&auditComment=${auditForm.auditComment}`,
      ''
    )
    ElMessage.success('审核成功')
    showAuditDialog.value = false
    fetchPurchases(pagination.current)
  } catch (e) {
    console.error(e)
    ElMessage.error('审核失败')
  }
}

// 更新实际数量
const handleUpdateActualQuantity = (row) => {
  actualQuantityForm.purchaseId = row.purchaseId
  actualQuantityForm.actualQuantity = row.actualQuantity || 0
  showActualQuantityDialog.value = true
}

// 提交实际数量
const submitActualQuantity = async () => {
  try {
    // 这里假设有一个更新实际数量的API
    await axios.post(
      import.meta.env.VITE_API_URL + `materialPurchase/updateActualQuantity/${actualQuantityForm.purchaseId}?actualQuantity=${actualQuantityForm.actualQuantity}`,
      ''
    )
    ElMessage.success('更新实际数量成功')
    showActualQuantityDialog.value = false
    fetchPurchases(pagination.current)
  } catch (e) {
    console.error(e)
    ElMessage.error('更新实际数量失败')
  }
}

// 提交生产计划
const submitAddPlan = async () => {
  if (!addPlanFormRef.value) return
  
  try {
    await addPlanFormRef.value.validate()
    // 这里假设有一个添加生产计划的API
    await axios.post(
      import.meta.env.VITE_API_URL + 'productionPlan/save',
      addPlanForm
    )
    ElMessage.success('添加生产计划成功')
    showAddPlanDialog.value = false
    // 重置表单
    addPlanForm.planName = ''
    addPlanForm.planDescription = ''
    addPlanForm.startDate = ''
    addPlanForm.endDate = ''
    addPlanForm.planQuantity = 0
  } catch (e) {
    console.error(e)
    ElMessage.error('添加生产计划失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!addFormRef.value) return
  
  try {
    await addFormRef.value.validate()
    const url = editPurchaseId.value
      ? import.meta.env.VITE_API_URL + 'materialPurchase/update'
      : import.meta.env.VITE_API_URL + 'materialPurchase/save'
    
    const params = {
      ...addForm,
      purchaseId: editPurchaseId.value
    }
    
    await axios.post(url, params)
    ElMessage.success(editPurchaseId.value ? '修改成功' : '添加成功')
    showAddDialog.value = false
    editPurchaseId.value = null
    fetchPurchases(1)
  } catch (e) {
    console.error(e)
    ElMessage.error(editPurchaseId.value ? '修改失败' : '添加失败')
  }
}

onMounted(() => {
  fetchPurchases(1)
  fetchDeptList()
})

// 显示详情对话框
const showDetail = (row) => {
  selectedPurchase.value = row
  showDetailDialog.value = true
}
</script>

<style scoped>
@import '@/styles/views.css';
</style>